<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;

class Authenticate
{
    /**
     * The authentication guard factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
    protected $auth;

    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory  $auth
     * @return void
     */
    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if ($this->auth->guard($guard)->guest()) {
            return response('Unauthorized.', 401);
        }

        return $next($request);

        // if you haed package (tymon/jwt-auth) as your default jwt driver
        // you can use this code and modify the env file
        // Notice :: you should import the packages by your self 
        /////////////////////////////////////////////////////
        // $headers = [];
        // if ($this->auth->guard($guard)->guest()) {
        //     try {
        //         $newToken = $this->auth->guard($guard)->refresh();
        //         $headers = ['Authorization' => 'Bearer ' . $newToken];
        //     }catch (JWTException $exception){
        //         $content = [
        //             'message' => '请重新登录',
        //             'errcode' => 401
        //         ];
        //         return response($content, 401);
        //     }
        // }
        // return $next($request)->withHeaders($headers);
    }
}
